using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Machinery.Queries;

/// <summary>
/// 设备分页查询命令。
/// </summary>
public sealed record GetMachineryListWithPagedQuery(
    long? LineId,
    string? MachineryCode,
    string? MachineryName,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<EquipMachineryDto>>>;

internal sealed class GetMachineryListWithPagedQueryHandler(IRepository<EquipMachinery> repo) : IRequestHandler<GetMachineryListWithPagedQuery, IResult<PagedList<EquipMachineryDto>>>
{
    public async Task<IResult<PagedList<EquipMachineryDto>>> Handle(GetMachineryListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(m => m.Line)
            .Includes(m => m.Workstation)
            .WhereIF(request.LineId > 0, m => m.LineId == request.LineId)
            .WhereIF(!string.IsNullOrWhiteSpace(request.MachineryCode), m => m.MachineryCode.Contains(request.MachineryCode!))
            .WhereIF(!string.IsNullOrWhiteSpace(request.MachineryName), m => m.MachineryName.Contains(request.MachineryName!))
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<EquipMachineryDto>>());
    }
}
